const db = require("../libs/DBHelper");
const jwt = require("jwt-simple");
const md5 = require("md5");

class UserController {
  // post
  async login(req, res) {
    let sql = "SELECT `uId`,`phone` FROM `userinfo` WHERE `phone`=? AND `password`=?;";
    let params = [
      req.body.name,
      req.body.password
    ];
    let results = await db.exec(sql, params);
    let isLogin = results && results.length >= 1;
    if (isLogin) {
      // 登录成功，就生成token
      // let token = jwt.encode(results[0], md5("cs2201"), 'HS512');
      res.json({
        code: 200,
        msg: "登录成功",
        data: results[0],
        // token
      })
    } else {
      res.json({
        code: 401,
        msg: "手机号输入错误或密码错误"
      })
    }
  }
  async register(req, res) {
    let sql = "INSERT INTO `userinfo`(`phone`,`password`)VALUES(?,?);";
    let params = [
      req.body.phone,
      req.body.password
    ];
    try {
      let results = await db.exec(sql, params);
      let isReg = results && results.affectedRows >= 1;
      res.json({
        code: isReg ? 200 : 400,
        msg: isReg ? "注册成功" : "注册失败"
      })
    } catch (error) {
      res.json({
        code: 400,
        msg: "注册失败",
        error
      })
    }
  }
}

module.exports = new UserController;